package com.lock.type;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @Author: tgy
 * @Date: 2020-07-24 10:31
 */
interface Cache{

    void add(String key,Object value);

    Object get(String key);
}

/**
 *
 * 读写锁
 *
 *  写写共享
 *  读写互斥
 *  读读互斥
 */
class MyCache implements Cache{

    private volatile Map<String,Object> store = new HashMap<>();

    private ReadWriteLock readWriteLock = new ReentrantReadWriteLock();


    @Override
    public void add(String key, Object value) {


        readWriteLock.writeLock().lock();

        try {
            System.out.println("==========写之前=============");
            store.put(key,value);
            System.out.println("----------写之后-------------");
        }finally {

            readWriteLock.writeLock().unlock();
        }

    }

    @Override
    public Object get(String key) {


        readWriteLock.readLock().lock();

        try {
            System.out.println("#############读之前##############");
            return store.get(key);

        }finally {
            System.out.println("**************读之后**************");
            readWriteLock.readLock().unlock();
        }
    }
}


public class ReadWriteLockTest {


    public static void main(String[] args) {

//        CyclicBarrier

        Cache cache = new MyCache();

        for ( int i = 0; i < 100; i++) {
            int j = i;
            new Thread(()->{

                cache.add("key" + String.valueOf(j),UUID.randomUUID().toString().substring(0,6));

            }).start();

        }

        for (int i = 0; i < 100; i++) {

            int j = i;
            new Thread(()->{

                System.out.println(cache.get("key" + String.valueOf(j)));

            }).start();

        }


        while (Thread.activeCount() > 2){

            Thread.yield();
        }

    }
}
